package com.ruoyi.yljf.service.impl;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.yljf.domain.*;
import com.ruoyi.yljf.domain.vo.*;
import com.ruoyi.yljf.mapper.*;
import com.ruoyi.yljf.service.ICoursePackageService;
import com.ruoyi.yljf.service.IQuestionService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import javax.annotation.Resource;

/**
 * 题目表Service业务层处理
 *
 * @author metaee
 * @date 2025-03-22
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

	@Resource
    private QuestionMapper questionMapper;

	@Resource
	private CourseMapper courseMapper;

	@Resource
	private ICoursePackageService coursePackageService;

	@Resource
	private CoursePackageMapper coursePackageMapper;

	@Resource
	private ExerciseQuestionMapper exerciseQuestionMapper;

	@Resource
	private UserQuestionRecordMapper userQuestionRecordMapper;

	@Resource
	private PaperTaxonMapper paperTaxonMapper;

	@Resource
	private TestPaperMapper testPaperMapper;

	@Override
	public List<ExamVO> qyeryExamList() {
		//取所有课程 id  name
 		List<ExamVO> coursePracticeVOS = courseMapper.getExamVO();
		AtomicReference<Long> sum = new AtomicReference<>((long) 0);
		coursePracticeVOS.forEach(examVO -> {
			List<PaperTaxon> paperTaxons = paperTaxonMapper.selectList(new LambdaQueryWrapper<>(PaperTaxon.class)
					.eq(PaperTaxon::getCourseId, examVO.getId()));
			List<PaperVO> paperVOS = BeanUtil.copyToList(paperTaxons,PaperVO.class);
			paperVOS.forEach(paperVO -> {
				Long count = testPaperMapper.selectCount(new LambdaQueryWrapper<>(TestPaper.class)
						.eq(TestPaper::getPaperTaxonId, paperVO.getTaxonId())
				);
				paperVO.setTotalCount(count);
				sum.set(Long.sum(sum.get(), count));
			});
			examVO.setPaper(paperVOS);
			examVO.setExamCount(sum.get());
			sum.getAndSet(0L);
		});
		//查找课程考试总题目数
		return coursePracticeVOS;
	}

	/**
	 * 通过课程id得到课程练习题统计数据：课程、章节（名，全部题目数，当前用户以完成题目数）
	 * @param id  用户id
	 * @return  课程练习题统计数据：课程、章节（名，全部题目数，当前用户以完成题目数）
	 */
	@Override
	public CourseStatisticsVO getCourseStatistics(Long id) {
		Course course = courseMapper.selectById(id);
		CourseStatisticsVO result = new CourseStatisticsVO();
		result.setCourseName(course.getName());
		result.setCourseId(course.getId());

		List<CoursePackage> coursePackages = coursePackageMapper.selectList(
				new LambdaQueryWrapper<>(CoursePackage.class)
						.eq(CoursePackage::getCourseId, id)
						.orderByAsc(CoursePackage::getSort)
		);

		// 统计全部题目数 和 当前用用户完成题目数
		Long userId = SecurityUtils.getUserId();  // 未登录抛出用户登录过期
		List<PackageStatics> packageStaticsList = coursePackages.stream()
				.map(coursePackage -> {
					PackageStatics packageStatics = new PackageStatics();
					packageStatics.setPackageName(coursePackage.getName());
					packageStatics.setTitle(coursePackage.getTitle());
					packageStatics.setSort(coursePackage.getSort());
					packageStatics.setPackageId(coursePackage.getId());

					LambdaQueryWrapper<ExerciseQuestion> wrapper = new LambdaQueryWrapper<>(ExerciseQuestion.class)
							.eq(ExerciseQuestion::getCourseId, id)
							.eq(ExerciseQuestion::getPackageId, coursePackage.getId())
							.orderByAsc(ExerciseQuestion::getSort);
					// 章节全部题目数
					Long count = exerciseQuestionMapper.selectCount(wrapper);
					packageStatics.setPackageTotal(count);

					// 查询用户完成题目数
					Long complete = userQuestionRecordMapper.selectCount(new LambdaQueryWrapper<>(UserQuestionRecord.class)
							.eq(UserQuestionRecord::getUserId, userId)
							.eq(UserQuestionRecord::getCourseId, coursePackage.getCourseId())
							.eq(UserQuestionRecord::getPackageId, coursePackage.getId()));
					packageStatics.setPackageComplete(complete);

					return packageStatics;
				}).collect(Collectors.toList());

		Long total = 0L, complete = 0L;
		for (PackageStatics packageStatics: packageStaticsList) {
			total += packageStatics.getPackageTotal();
			complete += packageStatics.getPackageComplete();
		}

		result.setCourseQuestionTotal(total);
		result.setCourseQuestionComplete(complete);
		result.setPackageStatics(packageStaticsList);

		return result;
	}

	/**
	 * 通过课程Id和课程章节Id获取试题列表
	 * @param courseId：课程Id
	 * @param packageId：课程章节Id
	 * @return：返回对应试题列表
	 */
	@Override
	public List<QuestionVO> getQuestionList(Long courseId, Long packageId) {
		if(!isPermission(courseId, packageId)) {
			throw new RuntimeException("用户访问此章节试题权限，请购买后重新访问");
		}

		// 对应课程章节全部试题id
		List<Question> questions = questionList(courseId, packageId);
		List<QuestionVO> collect = questions.stream()
				.map(question -> {
					QuestionVO questionVO = new QuestionVO(question);
					UserQuestionRecord userQuestionRecord = getUserQuestionRecord(courseId, packageId, question.getId());
					if(userQuestionRecord == null) {  // 用户未做过此题
						questionVO.setComplete(false);
					} else {  // 用户做过此题
						questionVO.setComplete(true);
						questionVO.setUserOption(userQuestionRecord.getUserOption());
					}
					return questionVO;
				}).collect(Collectors.toList());

		return collect;
	}

	/**
	 * 通过考试id获取考试所有题目
	 * @param taxonId
	 * @return
	 */
	@Override
	public List<QuestionVO> getPaperQuestionList(Long taxonId) {
		List<Long> list = questionMapper.questionQuestionByIds(taxonId);
		List<Question> questions = questionMapper.questionListByIds(list);
		List<QuestionVO> result = questions.stream()
				.map(question -> {
					QuestionVO questionVO = new QuestionVO(question);
					return questionVO;
				}).collect(Collectors.toList());
		return result;
	}

	// 获取对应章节所有题目数
	private List<Question> questionList(Long courseId, Long packageId){
		List<ExerciseQuestion> exerciseQuestions = exerciseQuestionMapper.selectList(new LambdaQueryWrapper<>(ExerciseQuestion.class)
				.select(ExerciseQuestion::getQuestionId)
				.eq(ExerciseQuestion::getCourseId, courseId)
				.eq(ExerciseQuestion::getPackageId, packageId)
				.orderByAsc(ExerciseQuestion::getSort));
		List<Long> ids = exerciseQuestions.stream()
				.map(exerciseQuestion -> exerciseQuestion.getQuestionId())
				.collect(Collectors.toList());
		List<Question> questions = questionMapper.questionListByIds(ids);
		return questions;
	}

	// 获取对应课程章 节用户完成题目id集合
	private Set<Long> completeQuestion(Long courseId, Long packageId) {
		List<UserQuestionRecord> userQuestionRecords = userQuestionRecordMapper.selectList(new LambdaQueryWrapper<>(UserQuestionRecord.class)
				.select(UserQuestionRecord::getQuestionId)
				.eq(UserQuestionRecord::getUserId, SecurityUtils.getUserId())
				.eq(UserQuestionRecord::getCourseId, courseId)
				.eq(UserQuestionRecord::getPackageId, packageId));
		Set<Long> set = userQuestionRecords.stream()
				.map(userQuestionRecord -> userQuestionRecord.getQuestionId()).collect(Collectors.toSet());
		return set;
	}

	// 根据课程id，章节id，题目id获取用户对应做题记录
	private UserQuestionRecord getUserQuestionRecord(Long courseId, Long packageId, Long questionId) {
		UserQuestionRecord userQuestionRecord = userQuestionRecordMapper.selectOne(new LambdaQueryWrapper<>(UserQuestionRecord.class)
				.eq(UserQuestionRecord::getUserId, SecurityUtils.getUserId())
				.eq(UserQuestionRecord::getCourseId, courseId)
				.eq(UserQuestionRecord::getPackageId, packageId)
				.eq(UserQuestionRecord::getQuestionId, questionId));
		return userQuestionRecord;
	}

	// 是否有权限获取对应章节的试题权限
	private boolean isPermission(Long courseId, Long packageId) {
		LoginUser loginUser = SecurityUtils.getLoginUser();
		// TODO 查询当前用户是否能获取对应章节试题
		return true;
	}
}
